package com.hefan.robot.listener;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.cat.common.entity.ResultBean;
import com.cat.common.meta.ResultCode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hefan.common.ons.TopicRegistry;
import com.hefan.common.ons.TopicRegistryDev;
import com.hefan.common.ons.TopicRegistryTest;
import com.hefan.common.ons.listener.GLLMessageListener;
import com.hefan.common.util.MapUtils;
import com.hefan.live.bean.LivingRoomInfoVo;
import com.hefan.live.itf.LiveImOptService;
import com.hefan.live.itf.LivingRedisOptService;
import com.hefan.robot.configCenter.RobotConfigCenter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

/**
 * Created by nigle on 2016/12/12.
 */
@Component
public class RobotActionRandLightListener implements GLLMessageListener {

    Logger logger = LoggerFactory.getLogger(RobotActionRandLightListener.class);

    @Resource
    LiveImOptService liveImOptService;
    @Resource
    LivingRedisOptService livingRedisOptService;
    @Resource
    private RobotConfigCenter robotConfigCenter;

    @Override
    public TopicRegistry getTopicRegistry() {
        return TopicRegistry.HEFAN_ROBOT_ACTION_RAND_LIGHT_DELAY ;
    }

    @Override
    public TopicRegistryDev getTopicRegistryDev() {
        return TopicRegistryDev.HEFAN_ROBOT_ACTION_RAND_LIGHT_DELAY_DEV;
    }

    @Override
    public TopicRegistryTest getTopicRegistryTest() {
        return TopicRegistryTest.HEFAN_ROBOT_ACTION_RAND_LIGHT_DELAY_TEST;
    }

    /**
     * 机器人点亮直播间，只有泡泡
     * */
    @Override
    public Action consume(Message message, ConsumeContext consumeContext) {
        String realTopic = message.getTag();
//        logger.info("机器人随机点亮直播间-开始： receiver MessageListener topic: {}, realTopic : {}, msg_body: {}",
//                message.getTopic(), realTopic, new String(message.getBody()));
        logger.info("机器人随机点亮直播间-开始");
        try {
            Map map = new ObjectMapper().readValue(message.getBody(), Map.class);
            if (null != map && !map.isEmpty()) {
                String voStr = (String) map.get("vo");
                LivingRoomInfoVo vo = JSONObject.parseObject(voStr, LivingRoomInfoVo.class);
                if (null == vo) {
                    logger.info("RobotListenerVo解析失败");
                    return Action.CommitMessage;
                }

                if (!livingRedisOptService.isExistsLivingInfo_Hash(vo.getUserId())) {
                    logger.info("直播{}已经结束，停止发送随机点亮IM消息",vo.getLiveUuid());
                    return Action.CommitMessage;
                }
                if (!livingRedisOptService.IMSendCheck(vo.getUserId(),2)){
                    logger.info("太多了不能再发送随机点亮的IM消息了：{}",vo.getLiveUuid());
                    return Action.CommitMessage;
                }
                if (livingRedisOptService.getLivingUserCount_SortedSet(vo.getUserId()) == 0){
                    logger.info("直播间没人了，不发随机点亮消息了:{}",vo.getLiveUuid());
                    return Action.CommitMessage;
                }

                Map<String,String> propty = robotConfigCenter.getPublicConfig();
                //限制机器人动作数量阈值
                long robotActionMax = MapUtils.getLongValue(propty, "robot.action.max", 500);
                long numReal = livingRedisOptService.getLivingUserCountReal(vo.getUserId());
                if( numReal > robotActionMax){
                    logger.info("直播间人数已经达到{}，停止机器人随机点亮动作",numReal);
                    return Action.CommitMessage;
                }

                ResultBean rb = liveImOptService.lightRoomOnlyPop(vo.getChatRoomId(), vo.getLiveUuid());
                if (null != rb && rb.getCode() == ResultCode.SUCCESS.get_code()) {
                    logger.info("机器人：{}随机点亮直播间：{}发送IM成功，code：{}，msg：{}" ,vo.getUserId() , vo.getLiveUuid() ,String.valueOf(rb.getCode()) ,rb.getMsg());
                }else {
                    rb = liveImOptService.lightRoomOnlyPop(vo.getChatRoomId(), vo.getLiveUuid());
                    if (null != rb && rb.getCode() == ResultCode.SUCCESS.get_code()) {
                        logger.info("机器人：{}随机点亮直播间：{}发送IM成功，code：{}，msg：{}" ,vo.getUserId() , vo.getLiveUuid() ,String.valueOf(rb.getCode()) ,rb.getMsg());
                    }else {
                        rb = liveImOptService.lightRoomOnlyPop(vo.getChatRoomId(), vo.getLiveUuid());
                        if (null != rb && rb.getCode() == ResultCode.SUCCESS.get_code()) {
                            logger.info("机器人：{}随机点亮直播间：{}发送IM成功，code：{}，msg：{}" ,vo.getUserId() , vo.getLiveUuid() ,String.valueOf(rb.getCode()) ,rb.getMsg());
                        }else {
                            logger.info("机器人：{}随机点亮直播间：{}发送IM，尝试三次，还是失败了，code：{}，msg：{}" ,vo.getUserId() , vo.getLiveUuid() ,String.valueOf(rb.getCode()) ,rb.getMsg());
                        }
                    }
                }
                return Action.CommitMessage;
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(message.getTopic(), realTopic + " MessageListener ERROR：" + e.getMessage());
            return Action.CommitMessage;
        } finally {
            logger.info(message.getTopic(), realTopic + " MessageListener END");
            return Action.CommitMessage;
        }
    }

}
